<template>
  <div>
    <my-breadcrumb :items="['员工管理', '员工列表']"></my-breadcrumb>
    <div class="top">
      <Button type="primary" @click="showAddInput" style="float: left;margin-right: 10px;">添加员工</Button>
      <Form inline v-show="showSearchInput">
        <FormItem>
          <Input v-model="emPhone" placeholder="根据用户电话号码查找" @keyup.enter="searchUser"/>
        </FormItem>
        <FormItem>
          <Button type="primary" @click="searchUser">检索</Button>
        </FormItem>
      </Form>
    </div>
    <div>
      <Table :columns="emColumns" :data="emList"></Table>
    </div>
    <Modal v-model="showRoles">
      <div>
        <h3>当前角色</h3>
        <Tag closable v-for="(role, index) in roles" :key="index" @on-close="closeTag(role)">{{ role.name }}</Tag>
      </div>
      <div style="margin-top: 20px;">
        <h3>未拥有角色(点击赋予)</h3>
        <Button style="margin-right: 10px;" size="small" v-for="(r, index) in notHasRole" :key="index" @click="roleClick(r)">{{ r.name }}</Button>
      </div>
    </Modal>
    <Modal v-model="showAddUser" title="员工注册" :styles="{top: '16px'}" width="440">
      <div slot="footer"></div>
      <h3>点击用户显示二维码，再次点击可刷新</h3>
      <ul>
        <li v-for="(user, index) in searchUsers" :key="index" @click="userToCode(user.id)" class="user_li">
          <Avatar :src="user.profilePhotoPath" shape="square" size="large"></Avatar>
          <span>{{ user.nickname }}</span>
        </li>
      </ul>
      <div id="login_code"></div>
    </Modal>
  </div>
</template>

<script>
!function(a,b,c){function d(a){var c="default";a.self_redirect===!0?c="true":a.self_redirect===!1&&(c="false");var d=b.createElement("iframe"),e="https://open.weixin.qq.com/connect/qrconnect?appid="+a.appid+"&scope="+a.scope+"&redirect_uri="+a.redirect_uri+"&state="+a.state+"&login_type=jssdk&self_redirect="+c;e+=a.style?"&style="+a.style:"",e+=a.href?"&href="+a.href:"",d.src=e,d.frameBorder="0",d.allowTransparency="true",d.scrolling="no",d.width="300px",d.height="400px";var f=b.getElementById(a.id);f.innerHTML="",f.appendChild(d)}a.WxLogin=d}(window,document);
export default {
  name: 'employee',
  data () {
    return {
      url: {
        list: '/branch/employee/list',
        del: '/branch/employee/delete',
        roleList: '/admin/manager/permission/role/list',
        roleUpdate: '/admin/manager/user/role/update',
        search: '/branch/user/search'
      },
      emList: [],
      emColumns: [
        {
          title: '微信',
          align: 'center',
          render: (h, params) => {
            return h('div', [
              h('Avatar', {
                props: {
                  size: 'large',
                  src: params.row.profilePhotoPath
                }
              }),
              h('span', {
                style: {
                  lineHeight: '36px',
                  display: 'inline-block'
                }
              }, params.row.nickname)
            ])
          }
        },
        {
          title: '姓名',
          align: 'center',
          render: (h, params) => {
            return h('span', params.row.realName)
          }
        },
        {
          title: '手机',
          align: 'center',
          render: (h, params) => {
            return h('span', params.row.phone)
          }
        },
        {
          title: '加入时间',
          align: 'center',
          render: (h, params) => {
            return h('span', new Date(params.row.gmtCreate).toLocaleString())
          }
        },
        {
          title: '员工角色',
          align: 'center',
          render: (h, params) => {
            return h('span', params.row.roleListStr)
          }
        },
        {
          title: '操作(更换)',
          align: 'center',
          render: (h, params) => {
            return h('Button', {
              props: {
                type: 'primary',
                size: 'small'
              },
              on: {
                click: () => {
                  this.setUserRole(params.index)
                }
              }
            }, '修改角色')
          }
        },
        {
          title: '删除',
          align: 'center',
          render: (h, params) => {
            return h('Button', {
              props: {
                type: 'error'
              },
              on: {
                click: () => {
                  this.delEmployee(params.row)
                }
              }
            }, '删除')
          }
        }
      ],
      emPhone: '',
      showSearchInput: false,
      showRoles: false,
      // 员工拥有的角色
      roles: [],
      // 未拥有角色
      notHasRole: [],
      // 所有角色
      allRole: [],
      // 当前员工ID
      activeId: null,
      // 检索出来的用户
      searchUsers: [],
      showAddUser: false,

      // 二级密码
      password: ''
    }
  },
  methods: {
    searchUser () {
      let params = {
        phone: this.emPhone,
        pageQuery: {
          pageNum: 1,
          pageSize: 30
        }
      }
      this.$ajax.post(this.url.search, JSON.stringify(params))
        .then(res => {
          if (res.data.success) {
            this.searchUsers = res.data.data.pageInfo.list
            this.showAddUser = true
          }
        })
    },

    userToCode (id) {
      let formData = new FormData()
      formData.append('userId', id)
      this.$ajax.post('/admin/register/code/param', formData, {header: {'Content-Type': 'multipart/form-data'}})
        .then(res => {
          let obj = new WxLogin({
            self_redirect: false,
            id: "login_code",
            appid: res.data.appId,
            scope: "snsapi_login",
            redirect_uri: res.data.redirectUri,
            state: res.data.state,
            style: "black"
          })
        })
    },

    showAddInput () {
      this.showSearchInput = true
    },

    setUserRole (index) {
      this.activeId = this.emList[index].id
      this.roles = []
      this.notHasRole = []
      let role = this.emList[index].roleListStr.split(',')
      this.allRole.forEach(item => {
        if (role.indexOf(item.name) !== -1) {
          this.roles.push(item)
        } else {
          this.notHasRole.push(item)
        }
      })
      this.showRoles = true
    },
    closeTag (role) {
      this.$Modal.confirm({
        title: '移除角色',
        content: '<p>你确定移除该员工的' + role.name + '角色吗？</p>',
        loading: true,
        onOk: () => {
          this.$ajax.post(this.url.roleUpdate, {userId: this.activeId, adds: [], removes: [role.id]})
            .then(res => {
              if (res.data.success) {
                this.$Modal.remove()
                this.notHasRole.push(role)
                this.initList()
                this.roles.forEach((item, index) => {
                  if (item.id === role.id) {
                    this.roles.splice(index, 1)
                  }
                })
              }
            })
        }
      })
    },
    roleClick (role) {
      this.$Modal.confirm({
        title: '赋予角色',
        content: '<p>你确定赋予该员工的' + role.name + '角色吗？</p>',
        loading: true,
        onOk: () => {
          this.$ajax.post(this.url.roleUpdate, {userId: this.activeId, adds: [role.id], removes: []})
            .then(res => {
              if (res.data.success) {
                this.$Modal.remove()
                this.roles.push(role)
                this.initList()
                this.notHasRole.forEach((item, index) => {
                  if (item.id === role.id) {
                    this.notHasRole.splice(index, 1)
                  }
                })
              }
            })
        }
      })
    },

    delEmployee (user) {
      this.$Modal.confirm({
        title: '删除员工',
        render: h => {
          return h('Input', {
            props: {
              placeholder: '输入二级密码删除员工',
              type: 'password'
            },
            on: {
              input: (e) => {
                this.password = e
              }
            }
          })
        },
        onOk: () => {
          this.$ajax.post(this.url.del, {userId: user.id, password: this.password})
            .then(res => {
              if (res.data.success) {
                this.initList()
                this.$Message.success('删除成功')
              }
            })
        }
      })
    },

    initList () {
      this.$ajax.post(this.url.list)
        .then(res => {
          if (res.data.success) {
            this.emList = res.data.data
          }
        })
    },
    getRoles () {
      this.$ajax.post(this.url.roleList)
        .then(res => {
          if (res.data.success) {
            this.allRole = res.data.data
          }
        })
    }
  },
  created () {
    this.initList()
    this.getRoles()
  }
}
</script>

<style scoped>
 .top{
   margin-bottom: 10px;
   overflow: hidden;
 }
  #login_code{
    height: 400px;
    width: 300px;
    margin: 0 auto;
  }
  .user_li{
    padding: 8px;
    cursor: pointer;
  }
  .user_li:hover{
    background-color: #dddee1;
  }
</style>
